﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
using System.Web.Routing;
using Sharp.Infrastructure;
using Sharp.Infrastructure.IoC;
using Sharp.Platform.Interface;

namespace Sharp.Platform.Mvc
{
    public class TemplateMange
    {
        private readonly static TemplateOperateAction oa = new TemplateOperateAction();
        static TemplateMange()
        {
            var provider = ServiceLocator.Instance.GetService<ITemplateProvider>();


            oa.GatherOperate("Create", provider.Create);
            oa.GatherOperate("Details", provider.Details);
            oa.GatherOperate("Edit", provider.Edit);
            oa.GatherOperate("Index", provider.Index);


        }
        /// <summary>
        /// 获取模板
        /// </summary>
        /// <param name="requestContext"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string GetTemplate(RequestContext requestContext, object model)
        {
            var controller = requestContext.RouteData.Values["Controller"].ToString();
            var action = requestContext.RouteData.Values["Action"].ToString();
            var key = string.Format("{0}_{1}", controller, action);
            object obj;
#if DEBUG
            obj = null;
#else
            obj = HttpRuntime.Cache.Get(key);
#endif

            if (obj != null && File.Exists(WebServer.MapPath(obj.ToString())))
            {
                return obj.ToString();
            }
            else
            {
                string tempfile = WebServer.MapPath("~/Views/Temp/");
                if (!Directory.Exists(tempfile))
                {
                    Directory.CreateDirectory(tempfile);
                }

                string html = oa.ExecuteOperate(action, model);

                tempfile = "~/Views/Temp/" + controller + "_" + action + "_" + html.Md5() + ".cshtml";
                if (!File.Exists(WebServer.MapPath(tempfile)))
                {
                    File.WriteAllText(WebServer.MapPath(tempfile), html, new UTF8Encoding(true));
                }

                HttpRuntime.Cache.Add(key, tempfile, null, DateTime.Now.AddSeconds(3600), TimeSpan.Zero, CacheItemPriority.NotRemovable, null);

                return tempfile;
            }
        }
    }
}
